package redis

import (
	"context"
	"github.com/go-redis/redis/v8"
)

/*
   @author:zhongyang
   @date:2023/8/20
   @description:redis相关
*/

// LimitByLuaScript lua脚本，用于限制次数
func LimitByLuaScript(ctx context.Context, redisClient *redis.Client) bool {
	// lua 脚本完成十次限制
	script := `

		local exists = redis.call('EXISTS', 'email_count')
		if exists == 0 then
			redis.call('SET', 'email_count', 0)
			redis.call('EXPIRE', 'email_count', 3600)
		end

        local maxEmails = 10
        local emailCount = tonumber(redis.call('GET', 'email_count') or 0)

        if emailCount < maxEmails then
            redis.call('INCR', 'email_count')
            return "send_email"
        else
            return "limit_exceeded"
        end
    `
	result, err := redisClient.Eval(ctx, script, []string{}, []interface{}{}).Result()
	if err != nil {
		return false
	}

	switch result {
	case "send_email":
		return true
	case "limit_exceeded":
		return false
	}
	return false
}
